<?php
/**
 * Created by PhpStorm.
 * User: Rei
 * Date: 16/5/16
 * Time: 08:40
 * Mail: rei@king.moe
 */
date_default_timezone_set("Asia/Shanghai");
require 'ThinkPHP/Library/Vendor/PHPMailer/PHPMailerAutoload.php';

$time = date("Y/m/d H:i:s");
$log = "$time 推送开始: ";

try {
    //连接数据库
    $dbh = new PDO('mysql:host=localhost;dbname=pinpaper', 'root', '', array(
        PDO::ATTR_PERSISTENT=>true
    ));
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->exec('set names utf8');

    //开始查询用户推送数据
    //用户订阅的今日更新文章(推送只针对今天9:00之前未登陆的用户)

    //符合推送条件的用户
    $user_sql = "SELECT uid, email FROM pin_user WHERE logintime<:sendtime";
    $user_data = $dbh->prepare($user_sql);
    $stamp = strtotime(date("Y/m/d")) + 9*60*60;
    $user_data->execute(array(':sendtime'=> $stamp));
    $users = $user_data->fetchAll(PDO::FETCH_ASSOC);

    $num = 0;
    $fail = 0;

    foreach($users AS $user) {

        //遍历用户订阅数据并发送邮件
        $data_sql = "SELECT count(nid) AS num, topic, name FROM pin_news LEFT JOIN pin_topic ON pin_news.topic = pin_topic.tid WHERE topic IN (SELECT tid FROM pin_subscribe WHERE uid = :users) GROUP BY topic";
        $sub_data = $dbh->prepare($data_sql);
        $sub_data->execute(array(':users' => $user['uid']));
        $subs = $sub_data->fetchAll(PDO::FETCH_ASSOC);
        if(!empty($subs)){
            $content = "PinPaper用户您好，您订阅的:<br/><p>";
            foreach($subs AS $sub){
                $content .= $sub['name']." 更新了 ".$sub['num']." 篇文章<br/>";
            }
            $content .= "</p><p>发件时间：$time</p><p>此邮件为系统自动发出的，请勿直接回复。</p>";
            $result = sendMail($user['email'], '您在PinPaper的订阅更新啦', $content);
            if($result != true){
                $fail++;
                $log .= $result."\n";
            }
            $num++;
        }
    }
    //关闭数据库连接
    $dbh = null;

    $log .= "\n推送结束,共向". $num ."位推送更新," .$fail. "失败\n";

    echo $log;

} catch (PDOException $e) {
    print "数据库出错: " . $e->getMessage() . "\n";
    die();
}


function sendMail($to, $title, $content) {
    try {
        $mail = new PHPMailer(); //实例化
        $mail->IsSMTP(); // 启用SMTP
        $mail->Host='smtp.sina.cn'; //smtp服务器的名称
        $mail->SMTPAuth = TRUE; //启用smtp认证
        $mail->Username = "pinpaper@sina.cn"; //邮箱名
        $mail->Password = "pinpaper"; //邮箱密码
        $mail->From = "pinpaper@sina.cn"; //发件人地址
        $mail->FromName = "PinPaper"; //发件人姓名
        $mail->AddAddress($to,"尊敬的客户");
        $mail->WordWrap = 50; //设置每行字符长度
        $mail->IsHTML(TRUE); // 是否HTML格式邮件
        $mail->CharSet='UTF-8'; //设置邮件编码
        $mail->Subject =$title; //邮件主题
        $mail->Body = $content; //邮件内容
        $mail->AltBody = "这是一个纯文本的身体在非营利的HTML电子邮件客户端"; //邮件正文不支持HTML的备用显示
        return $mail->Send();
    } catch (phpmailerException $e) {
        return "邮件发送失败：".$e->errorMessage()."\n";
    }
}